const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

/**
 * 自定义Promise
 */
class MyPromise {
  #status = PENDING; // 初始状态为pending, 成功为 fulfiled, 失败为 rejected
  #result = undefined; // 存储成功的值
  constructor(executor) {
    this.onResolvedCallbacks = []; // 存储成功的回调 onResolvedCallbacks
    this.onRejectedCallbacks = []; // 存储失败的回调

    // 定义resolve函数
    const resolve = (value) => {
      if (this.#status !== PENDING) return;
      this.#status = FULFILLED;
      this.#result = value;
      this.onResolvedCallbacks.forEach((fn) => fn()); // 执行所有成功的回调
    };
    const reject = (reason) => {
      if (this.#status !== PENDING) return;
      this.#status = REJECTED;
      this.#result = reason;
      this.onRejectedCallbacks.forEach((fn) => fn()); // 执行所有失败的回调
    };
    try {
      // 立即执行executor函数
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }
  then(onResolved, onRejected) {
    console.log("onResolved", onResolved);
    console.log("onRejected", onRejected);
    // 如果 onResolved 或 onRejected 不是函数，提供默认值
    onResolved =
      typeof onResolved === "function" ? onResolved : (value) => value;
    onRejected =
      typeof onRejected === "function"
        ? onRejected
        : (reason) => {
            throw reason;
          };
    return new MyPromise((resolve, reject) => {
      const handleFulfilled = () => {
        try {
          setTimeout(() => {
            const x = onResolved(this.#result);
            resolve(x);
          }, 0);
        } catch (error) {
          reject(error);
        }
      };
      const handleRejected = () => {
        try {
          setTimeout(() => {
            const x = onRejected(this.#result);
            resolve(x);
          }, 0);
        } catch (error) {
          console.log("56:error", error);
          reject(error);
        }
      };
      if (this.#status === FULFILLED) {
        handleFulfilled();
      } else if (this.#status === REJECTED) {
        handleRejected();
      } else {
        // 异步任务
        this.onResolvedCallbacks.push(handleFulfilled); // 存储成功的回调
        this.onRejectedCallbacks.push(handleRejected); // 存储失败的回调
      }
    });
  }
  catch(onRejected) {
    return this.then(null, onRejected);
  }
  static all(promises) {
    return new MyPromise((resolve, reject) => {
      const results = [];
      let count = 0;
      promises.forEach((promise, index) => {
        console.log("promise", promise);
        MyPromise.resolve(promise)
          .then((value) => {
            results[index] = value;
            count++;
            if (count === promises.length) {
              resolve(results);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    });
  }
  // 静态方法 resolve
  static resolve(value) {
    if (value instanceof MyPromise) {
      return value;
    }
    return new MyPromise((resolve) => resolve(value));
  }
}
export default MyPromise;
